import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by huangyifeng on 2019/1/25.
 */
public class JsoupUtil {

    public Document jsoupConnect(String urlstr, int retry) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            URL url = new URL(urlstr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            Document communityDetail = Jsoup.parse(connection.getInputStream(), "gbk", urlstr);
            if (communityDetail == null) {
                jsoupConnect(urlstr, retry);
            }
            return communityDetail;
        } catch (Exception e) {
            if (retry > 999999999) {
                return null;
            }
            System.out.println(retry + "-正在重试...");
            return jsoupConnect(urlstr, ++retry);
        }
    }

    public void writeObject(Object obj, File file) throws Exception {
        // 将数据写入文件
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(obj);
        } finally {
            if (oos != null) {
                oos.close();
            }
        }
    }
}
